package com.kichina.parking.module.message.socket.message;

import com.alibaba.fastjson.JSONObject;
import com.kichina.parking.controller.parking.handler.YardStatusInfoHandler;
import com.kichina.parking.module.message.socket.IMessageHandler;
import com.kichina.parking.module.message.socket.SocketStorageDeal;
import com.kichina.parking.module.message.socket.bean.BaseSocketResponse;
import com.kichina.parking.module.message.socket.enums.MessageTypeEnum;
import com.kichina.parking.service.logic.bean.YardStatusInfo;
import io.vertx.core.net.NetSocket;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Surging
 * @version 1.0
 * @ClassName SocketMessageHeartHandler
 * @date 2022-06-17 14:44
 * @desc 心跳消息处理
 */
@Component
@Order(Byte.MIN_VALUE + 1)
@Slf4j
public class HeartHandler implements IMessageHandler {

    /**每10次心跳更新一次车场在线状态表**/
    public static ConcurrentHashMap<String, Integer> heartRecordMap = new ConcurrentHashMap<>();

    private final YardStatusInfoHandler yardStatusInfoHandler;

    public HeartHandler(YardStatusInfoHandler yardStatusInfoHandler) {
        this.yardStatusInfoHandler = yardStatusInfoHandler;
    }

    @Override
    public void handler(JSONObject jsonObject, NetSocket netSocket) {
        SocketStorageDeal.sendResponse(netSocket, BaseSocketResponse.buildHeartSuccess());
        Integer heartRecord = heartRecordMap.get(netSocket.writeHandlerID());
        if (Objects.isNull(heartRecord)){
            heartRecordMap.put(netSocket.writeHandlerID(), 1);
        }else {
            if (heartRecord>=15){
                YardStatusInfo yardStatusInfo = new YardStatusInfo();
                yardStatusInfo.setIsOnline(true);
                yardStatusInfo.setYardKey((String) jsonObject.get("parkid"));
                //添加或更新车场在线状态
                yardStatusInfoHandler.saveOrUpdateYardInfo(yardStatusInfo);
                heartRecordMap.put(netSocket.writeHandlerID(), 0);
            }else {
                heartRecordMap.put(netSocket.writeHandlerID(), heartRecord + 1);
            }
        }
    }

    @Override
    public boolean check(JSONObject jsonObject) {
        return MessageTypeEnum.HEART_BEAT.getValue().equals(jsonObject.get("service"));
    }

    @Override
    public boolean interrupt() {
        return true;
    }
}
